export default {

	data() {
		return {


			messageList: [],
			scrollTop: 0,


			//文字输入内容
			comment: "",
			page: 1,
			pageSize: 10,


			isSend:false,



			messages: [{
				"role": "system",
				"content": "你的名字叫AI小助手，是一个聊天机器人, 无法回答和政治有关的问题."
			}],


		};
	},
	onLoad(options) {
		var messages = uni.getStorageSync("chat");
		if (messages) {
			this.messages = messages;
		}
		this.$refs.paging.scrollToBottom();
	},
	onPageScroll(e) {

		if (e.scrollTop < 10) {
			console.log("滚动距离为：" + e.scrollTop);
			// this.$refs.paging.doChatRecordLoadMore();
		}
	},
	methods: {

		queryList(pageNo, pageSize) {
			this.page = pageNo;
			this.pageSize = pageSize;
			this.getMessageList();
		},


		getMessageList() {
			this.$refs.paging.complete([])

		},
		deleteInfo() {
			uni.showModal({
				title:"确认要删除问答记录么？",
				success: (res) => {
					if (res.confirm) {
						uni.removeStorageSync("chat");
						this.messages = [];
					}
				}
			})
		},
		sendMessage() {
			if (!this.comment || this.comment.length == 0) {
				return;
			}
			if(!this.$util.checkCount()) {
				return;
			}
			var self = this;
			// sendMessage

			var messages = JSON.parse(JSON.stringify(this.messages));
			messages.push({
				role: 'user',
				content: this.comment,
				createTime:new Date().format("yyyy-MM-dd hh:mm:ss")
			});
			this.isSend = true;
			this.messages = JSON.parse(JSON.stringify(messages));
			
			uni.setStorageSync("chat",this.messages);
			this.comment = "";
			this.$refs.paging.scrollToBottom();
			
			uniCloud.callFunction({
				name: 'chat',
				data: {
					messages: this.messages
				}
			}).then(res => {

				console.log(res);
				var messages = JSON.parse(JSON.stringify(this.messages));
				messages.push({
					role: 'assistant',
					content: res.result.reply,
					createTime:new Date().format("yyyy-MM-dd hh:mm:ss")
				});
				this.isSend = false;
				this.messages = JSON.parse(JSON.stringify(messages));
				uni.setStorageSync("chat",this.messages);
				this.$refs.paging.scrollToBottom()
				this.$util.useCount();
				
			});

		},

		getName(model) {
			var name = ""
			if (model.role.indexOf('user') != -1) {
				name =
					"<div style='font-size:12px;width:50px;heigth:50px;border-radius: 5px;background-color: #5F96F5;color:#fff;text-align: center;line-height: 50px;'>我</div>"
			} else if (item.role.indexOf('assistant') != -1) {

				name =
					"<div style='font-size:18px;width:50px;heigth:50px;border-radius: 5px;background-color: #5F96F5;color:#fff;text-align: center;line-height: 50px;'>Ai助手</div>"
			}
			return name;
		},

		dateFormatter(time) {
			time = time.replace(/-/g, '/');

			var timestamp = new Date(time).getTime();

			var minute = 1000 * 60;
			var hour = minute * 60;
			var day = hour * 24;
			var halfamonth = day * 15;
			var month = day * 30;
			var year = day * 365;
			var now = new Date().getTime();
			var diffValue = now - timestamp;
			var result;
			if (diffValue < 0) {
				return;
			}
			var yearC = diffValue / year;
			var monthC = diffValue / month;
			var weekC = diffValue / (7 * day);
			var dayC = diffValue / day;
			var hourC = diffValue / hour;
			var minC = diffValue / minute;
			if (yearC >= 1) {
				result = this.dateFtt(time, 'yyyy-MM-dd')
			} else if (monthC >= 1) {
				result = this.dateFtt(time, 'MM-dd hh:mm')
			} else if (weekC >= 1) {
				result = this.dateFtt(time, 'MM-dd hh:mm');
			} else if (dayC >= 1) {
				result = this.dateFtt(time, 'MM-dd hh:mm');
			} else if (hourC >= 1) {
				result = this.dateFtt(time, 'hh:mm')
			} else if (minC >= 1) {
				result = "" + parseInt(minC) + "分钟前";
			} else
				result = "刚刚";
			return result;
		},
		dateFtt(time, fmt) { //author: meizz 
			var date = new Date(time)
			var o = {
				"M+": date.getMonth() + 1, //月份 
				"d+": date.getDate(), //日 
				"h+": date.getHours(), //小时 
				"m+": date.getMinutes(), //分 
				"s+": date.getSeconds(), //秒 
				"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
				"S": date.getMilliseconds() //毫秒 
			};
			if (/(y+)/.test(fmt))
				fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
			for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt))
					fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
						.length)));
			return fmt;
		},
		dateFormat(fmt, date) {
			let ret;
			const opt = {
				"y+": date.getFullYear().toString(), // 年
				"M+": (date.getMonth() + 1).toString(), // 月
				"d+": date.getDate().toString(), // 日
				"h+": date.getHours().toString(), // 时
				"m+": date.getMinutes().toString(), // 分
				"s+": date.getSeconds().toString() // 秒
				// 有其他格式化字符需求可以继续添加，必须转化成字符串
			};
			for (let k in opt) {
				ret = new RegExp("(" + k + ")").exec(fmt);
				if (ret) {
					fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
				};
			};
			return fmt;
		},
	}
}

Date.prototype.format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
			"00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}